// 资源管理
import React, { Component } from "react";
import {Button, Modal, Input, Form, Select, Row, Col, message, Space, Typography } from 'antd'
import GoBack from '@/components/TheGoBack'
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import ChooseGoods from './component/chooseGoods'
import TheImage from '@/components/TheImage'
import TheButton from "@/components/TheButton";
import {
    apiGetThirdChannelGoodsRelationPage,
    apiGetThirdChannelGoodsRelationAdd,
    apiGetThirdChannelGoodsRelationDel,
    apiGetThirdChannelDetail
} from "@/request/tripartiteMall/channelManagement";

const {confirm} = Modal;
const { Paragraph ,Link} = Typography;
export default class ChannelManagement extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.GoodsRef = React.createRef()
        this.state = {
            columns: [
                {
                    title: '频道ID',
                    dataIndex: 'channelId',
                    key: 'channelId'
                },
                {
                    title: '频道名称',
                    dataIndex: 'channelName',
                    key: 'channelName'
                },
                {
                    title: '备注',
                    dataIndex: 'remark',
                    key: 'remark'
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime'
                },
            ],
            goodsColumns: [
                {
                    title: '商品ID',
                    dataIndex: 'thirdGoodsId',
                    key: 'thirdGoodsId'
                },
                {
                    title: '商品来源',
                    dataIndex: 'thirdType',
                    key: 'thirdType'
                },
                {
                    title: '商品图片',
                    dataIndex: 'mainPic',
                    key: 'mainPic',
                    render: (text, render) => {
                        if (text) {
                            let arr = text.split(',')
                            return <Space>
                                {
                                    arr.map(v => {
                                        return <TheImage src={v} width={80} height={80}/>
                                    })
                                }
                            </Space>
                        }
                    }
                },
                {
                    title: '商品名称',
                    dataIndex: 'title',
                    key: 'title',
                    onCell: () => {
                        return {
                            style: {
                                whiteSpace: 'break-spaces',
                                maxWidth: 200
                            }
                        }
                    },
                    render: (text, record) => {
                        return <Paragraph
                            ellipsis={{
                                rows: 3,
                                expandable: false,
                            }}
                            title={text}
                            style={{margin:0}}
                        >
                            {record.thirdType==='淘宝'?<Link href={record.itemLink} target="_blank">
                                {text}
                            </Link>:text}
                        </Paragraph>
                    }
                },
                {
                    title: '店铺名称',
                    dataIndex: 'shopName',
                    key: 'shopName'
                },
                {
                    title: '优惠券面额',
                    dataIndex: 'couponPrice',
                    key: 'couponPrice',
                    render: (text, record) => {
                        return <Space direction={'vertical'}>
                            <span>
                                <React.$Price price={text || 0}/>
                            </span><
                            span>{record.couponTotalNum}张</span>
                        </Space>
                    }
                },
                {
                    title: '券后价',
                    dataIndex: 'actualPrice',
                    key: 'actualPrice',
                    render: (text, record) => {
                        return <React.$Price price={text || 0}/>
                    }
                },
                {
                    title: '操作',
                    dataIndex: 'operate',
                    key: 'operate',
                    render: (text, record) => {
                        return <TheButton haspermi={['tripartiteMall:channel:detailDel']} type="link" onClick={() => this.del([record.thirdGoodsId])}>删除</TheButton>
                    }
                },
            ],
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            dataSource: [],
            channelInfo: [],
            total: 11,
            isModalOpen: false,
            isViewModalOpen: false,
            selectedRowKeys: [],
            modalTitle: '',
            mode: false,
            channelId: null,
            thirdType: ''
        }
    }
    componentDidMount() {
        console.log(this.props.match.params.id)
        this.setState({
            channelId: this.props.match.params.id
        },()=>{
            this.getDetail()
            this.getData()
        })
    }
    getDetail = () => {
        apiGetThirdChannelDetail({channelId:this.state.channelId}).then(res=>{
            if (res.code===0){
                this.setState({
                    channelInfo: [res.data]
                })
            }
        })
    }
    getData = () => {
        apiGetThirdChannelGoodsRelationPage({
            ...this.state.pageData,
            channelId: this.state.channelId,
            thirdType: this.state.thirdType
        }).then(res => {
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    pageData: {
                        pageNo: res.pageNo,
                        pageSize: res.pageSize
                    },
                    total: res.totalCount
                })
            }
        })
    }
    // 分页
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize,
            },
        }, () => {
            this.getData()
        })
    };
    // 新增商品
    handleOk = () => {
        let goodsList = this.GoodsRef.current.onGetData();
        if (goodsList.length){
            let params = {
                thirdType: this.state.mode === 'tb'? 1 : 2,
                channelId: this.state.channelId,
                goodsList
            }
            apiGetThirdChannelGoodsRelationAdd({...params}).then(res=>{
                if (res.code === 0){
                    message.info(res.data)
                    this.setState({
                        isModalOpen: false
                    })
                    this.getData()
                }
            })
        }
        else {
            message.error('未选择商品')
        }
    }
    handleCancel = () => {
        this.formRef.current.resetFields()
        this.setState({
            isModalOpen: false
        })
    }
    onSelect = (selected, selectedRows) => {
        this.setState({
            selectedRowKeys: selected,
        })
    }
    handleChooseGoods = (type) => {
        this.setState({
            mode: type,
            isModalOpen: true,
            modalTitle: type === 'tb' ? '选择淘宝商品' : "选择拼多多商品"
        })
    }
    // 商品来源搜索
    onSelectSearch = (value) => {
        this.setState({
            thirdType: value
        }, () => {
            this.pageChange(1,10)
        })
    }
    del = (value) => {
        apiGetThirdChannelGoodsRelationDel({
            thirdGoodsIdList: value,
            channelId: this.state.channelId
        }).then(res=>{
            if (res.code === 0){
                message.success('删除成功')
                this.delToPageStatus()
            }
        })
    }
    // 删除时如果分页余数为1跳转上一页数据
    delToPageStatus = ()=>{
        let { pageData,total } = this.state
        if ((total%pageData.pageSize) === 1){
            this.pageChange(pageData.pageNo-1,pageData.pageSize)
        }
        else {
            this.pageChange(pageData.pageNo,pageData.pageSize)
        }
    }
    batchDel = () => {
        let {selectedRowKeys } = this.state
        console.log(selectedRowKeys)
        if (selectedRowKeys.length){
            confirm({
                title: '是否批量删除选中商品',
                content: '',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk:()=> {
                    this.del(selectedRowKeys)
                }
            });
        }
        else {
            message.error('未选择商品')
        }
    }
    render() {
        const { columns, dataSource, channelInfo, mode, pageData, total, isModalOpen, modalTitle, selectedRowKeys, goodsColumns } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelect,
        };
        return (
            <div className='p-layout-box'>
                <GoBack title={'频道详情'} history={this.props.history} />
                <TheTable
                    scroll={{ x: "max-content", y: "63vh" }}
                    columns={columns}
                    dataSource={channelInfo}
                    rowKey={(record) => record.channelId}
                />
                <h2 style={{ margin: '20px 0' }}>
                    <strong>商品列表</strong>
                </h2>
                <Form ref={this.formRef} onValuesChange={this.onValuesChange} style={{ margin: '0 20px' }} >
                    <Row style={{ width: "100%" }} >
                        <Col span={16}>
                            <Form.Item
                                label="商品来源"
                                layout={'inline'}
                            >
                                <Select
                                    style={{ width: 200 }}
                                    defaultValue={''}
                                    options={[
                                        {
                                            value: '',
                                            label: '全部',
                                        },
                                        {
                                            value: 1,
                                            label: '淘宝',
                                        },
                                        {
                                            value: 2,
                                            label: '拼多多',
                                        },
                                    ]}
                                    onChange={this.onSelectSearch}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8} style={{ textAlign: 'right' }}>
                            <Form.Item>
                                <TheButton haspermi={['tripartiteMall:channel:addTB']} type="primary" size={'middle'} onClick={() => this.handleChooseGoods('tb')}>新增淘宝商品</TheButton>&nbsp;&nbsp;&nbsp;&nbsp;
                                <TheButton haspermi={['tripartiteMall:channel:addPDD']} type="default" size={'middle'} otherStyle={{ background: '#1ac2c6', color: '#fff' }} onClick={() => this.handleChooseGoods('pdd')}>新增拼多多商品</TheButton>
                            </Form.Item>
                        </Col>

                    </Row>

                </Form>
                <div style={{ marginBottom: 20 }}>
                    <TheButton haspermi={['tripartiteMall:channel:batchDel']} type="danger" size={'middle'} onClick={this.batchDel}>批量删除</TheButton>
                </div>
                <TheTable
                    scroll={{ x: "max-content", y: "63vh" }}
                    columns={goodsColumns}
                    dataSource={dataSource}
                    rowSelection={rowSelection}
                    rowKey={(record) => record.thirdGoodsId}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
                {isModalOpen ? <Modal maskClosable={false} destroyOnClose={true} title={modalTitle} width="73%" visible={isModalOpen} onCancel={this.handleCancel} onOk={this.handleOk}> <ChooseGoods ref={this.GoodsRef} mode={mode}></ChooseGoods></Modal> : null}
            </div>
        )
    }
}
